package com.example.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.SpuImagesDao;
import com.example.gulimall.product.entity.SpuImagesEntity;
import com.example.gulimall.product.service.SpuImagesService;


@Service("spuImagesService")
public class SpuImagesServiceImpl extends ServiceImpl<SpuImagesDao, SpuImagesEntity> implements SpuImagesService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuImagesEntity> page = this.page(
                new Query<SpuImagesEntity>().getPage(params),
                new QueryWrapper<SpuImagesEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpuInfoImages(Long spuInfoId, List<String> images) {
        if (CollectionUtils.isNotEmpty(images)) {
            List<SpuImagesEntity> entities = images.stream().map(
                    a -> {
                        SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                        spuImagesEntity.setSpuId(spuInfoId);
                        spuImagesEntity.setImgUrl(a);
                        // d8c1b18a-faac-464c-8356-11c91c86788d_28f296629cca865e.jpg
                        spuImagesEntity.setImgName(subImageName(a));
                        return spuImagesEntity;
                    }
            ).collect(Collectors.toList());
            this.saveBatch(entities);
        }
    }

    private static String subImageName (String fullName) {
        char regex = '.';
        int index = fullName.indexOf(regex);
        return fullName.substring(0, index);
    }

}